<template>
  <div>
    <el-dialog title="" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="75%">
      <el-tabs v-model="activeName">
        <el-tab-pane :label="dialogStatus === 'update'? '编辑': '查看'" name="1">
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="110px" :disabled="this.dialogStatus !== 'update'">
            <el-row>
              <el-col :span="12">
                <el-form-item label="合同编码" prop="contractCode">
                  <el-input v-model="temp.contractCode" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同状态">
                  <el-select v-model="temp.contractState" clearable placeholder="请选择合同状态" style="width: 100%">
                    <el-option
                      v-for="item in stateOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="到货情况" prop="aogSituation">
                  <el-input v-model="temp.aogSituation" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发票" prop="invoice">
                  <el-input v-model="temp.invoice" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="付款方式" prop="paymentWay">
                  <el-select v-model="temp.paymentWay" clearable placeholder="付款方式" style="width: 100%">
                    <el-option
                      v-for="item in paymentWayOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同金额" prop="contractAmount">{{ temp.contractAmount }}</el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="合同备注" prop="contractComment">
              <el-input v-model="temp.contractComment" />
            </el-form-item>
          </el-form>
          <el-row>
            <el-button v-if="this.dialogStatus === 'update'" type="primary" class="filter-item" @click="addPayments()">+</el-button>
            <el-button type="primary" style="float: right;" class="filter-item" @click="btnIndent(temp)">采购订单</el-button>
            <el-button type="primary" style="float: right; margin-right: 5px;" class="filter-item" @click="btnPaymentOrder(temp)">付款单</el-button>
          </el-row>

          <el-table
            :data="payments"
            border
            style="width: 100%; margin-top: 5px;"
          >
            <el-table-column label="序号" type="index" />
            <el-table-column prop="proportion" label="占比" align="center" width="160px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.proportion" size="mini" v-show="!scope.row.editAmount && dialogStatus == 'update'"/>
                <span v-show="dialogStatus !== 'update'">{{ scope.row.proportion }}</span>
                <span v-show="scope.row.editAmount && dialogStatus == 'update'">{{ (scope.row.payAmount * 100.00 / temp.contractAmount).toFixed(2) }}
                <el-button type="primary" icon="el-icon-edit" @click.native="editPropBtn(scope.row)"></el-button>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="paymentDate" label="付款日期" align="center" width="160px">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.paymentDate"
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  style="width: 130px"
                  :disabled="dialogStatus !== 'update'"
                />
              </template>
            </el-table-column>
            <el-table-column label="付款金额">
              <template slot-scope="scope">
                <el-input v-model="scope.row.payAmount"  v-show="scope.row.editAmount && dialogStatus == 'update'"/>
                <span v-show="dialogStatus !== 'update'">{{ scope.row.payAmount }}</span>
                <span v-show="!scope.row.editAmount && dialogStatus == 'update'">{{ (scope.row.proportion * 0.01 * temp.contractAmount).toFixed(2) }}
                <el-button type="primary" icon="el-icon-edit" @click.native="editAmountBtn(scope.row)"></el-button>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="paymentSituation" label="付款情况" align="center" width="150px">
              <template slot-scope="scope">
                <el-select v-model="scope.row.paymentSituation" clearable placeholder="请选择付款情况" :disabled="dialogStatus !== 'update'">
                  <el-option
                    v-for="item in paymentStateOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="paymentApprovalState" label="付款审批状态" align="center" width="150px">
              <template slot-scope="scope">
                <el-select v-model="scope.row.paymentApprovalState" clearable placeholder="付款审批流程" :disabled="dialogStatus !== 'update'">
                  <el-option
                    v-for="item in paymentApprovalStateOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="paymentComment" label="付款备注" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.paymentComment" :disabled="dialogStatus !== 'update'" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120px">
              <template slot-scope="{row, index}">
                <el-button
                  v-permission="'purchase:contract:update'"
                  :disabled="dialogStatus !== 'update'"
                  style="margin-left: 5px"
                  type="text"
                  divided
                  @click.native="deletePayments(row, index)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane v-if="showDetail" label="详情" name="2">
          <el-table
            ref="contractDetailTable"
            show-summary
            :summary-method="getSummaries"
            :data="orderDetail"
            :span-method="arraySpanMethod"
            border
            style="width: 100%"
          >
            <el-table-column prop="orderCode" label="审批单编号" align="center" width="80px" />
            <el-table-column prop="orderDate" label="审批单日期" align="center" />
            <el-table-column prop="materialCode" label="设备编码" align="center" />
            <el-table-column prop="materialName" label="设备名称" align="center" width="150px" />
            <el-table-column prop="materialSpecification" label="规格" align="center" width="100px" />
            <el-table-column prop="unit" label="单位" align="center" width="50px" />
            <el-table-column prop="unitPrice" label="设备单价" align="center" width="50px" />
            <el-table-column prop="materialNum" label="采购数量" align="center" width="50px" />
            <el-table-column prop="materialTotalPrice" label="总价（元）" align="center" width="100px" />
            <el-table-column prop="projectName" label="项目（用途）" align="center" />
            <el-table-column prop="indentCode" label="采购订单编号" align="center" width="150px" />
            <el-table-column prop="supplierName" label="供应商" align="center" width="100px" />

          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus!=='view'" icon="el-icon-check" type="primary" @click="updateData">确定
        </el-button>
      </div>
    </el-dialog>
    <payment-order ref="conPaymentOrderRef" />
    <indent-order ref="conIndentOrderRef" />
  </div>

</template>

<script>
import { putAction, getAction } from '@/api/manage'
import { Message } from 'element-ui'
import paymentOrder from '@/views/purchase/contract/paymentOrder'
import indentOrder from '@/views/purchase/contract/indentOrder'

export default {
  name: '',
  components: {
    paymentOrder,
    indentOrder
  },
  props: {
    dialogStatus: {
      type: String,
      default: 'view'
    },
    showDetail: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      activeName: '1',
      contractId: undefined,
      dialogFormVisible: false,
      temp: {
        id: undefined,
        indentIds: '',
        indentCodes: '',
        contractCode: '',
        contractName: '',
        contractState: '',
        aogSituation: '',
        paymentSituation: '',
        paymentWay: '',
        invoice: '',
        contractComment: '',
        contractAmount: undefined
      },
      payments: [],
      orderDetail: [],
      paymentWayOptions: [{
        value: '预付100%',
        label: '预付100%'
      }, {
        value: '到货付30%，使用6个月付60%，1年后付10%',
        label: '到货付30%，使用6个月付60%，1年后付10%'
      }, {
        value: '到货付100%',
        label: '到货付100%'
      }, {
        value: '垫付',
        label: '垫付'
      }, {
        value: '其他',
        label: '其他'
      }],
      stateOptions: [{
        value: '未到合同',
        label: '未到合同'
      }, {
        value: '已到合同',
        label: '已到合同'
      }, {
        value: '完成',
        label: '完成'
      }],
      paymentStateOptions: [{
        value: '待付款',
        label: '待付款'
      }, {
        value: '待报销',
        label: '待报销'
      }, {
        value: '已完成',
        label: '已完成'
      }],
      paymentApprovalStateOptions: [{
        value: '审批中',
        label: '审批中'
      }, {
        value: '审批通过',
        label: '审批通过'
      }, {
        value: '交财务',
        label: '交财务'
      }],
      rules: {
        id: [{ required: true, message: '该项不能为空', trigger: 'change' }],
        contractName: [{ required: true, message: '该项不能为空', trigger: 'change' }]
      },
      orderCodeArr: undefined,
      projectNameArr: undefined,
      indentCodeArr: undefined,
      supplierNameArr: undefined
    }
  },
  created() {
  },
  methods: {
    getContractDetail() {
      getAction('/purchase/contract/queryDetailById?contractId=' + this.contractId).then(
        res => {
          const { data } = res
          this.temp = data
          this.payments = data.payments
          this.orderDetail = data.orderDetails
          this.merage()
        }
      )
    },
    addPayments() {
      let totalPro = 0
      if (this.payments !== undefined && this.payments.length > 0) {
        for (let i = 0; i < this.payments.length; i++) {
          if (this.payments[i].editAmount) {
            totalPro += parseFloat((this.payments[i].payAmount * 100.00 / this.temp.contractAmount).toFixed(2))
          } else if (typeof (this.payments[i].proportion) === 'string') {
            totalPro += parseFloat(this.payments[i].proportion)
          } else {
            totalPro += this.payments[i].proportion
          }
        }
      }
      this.payments.push({
        proportion: (100 - totalPro).toFixed(2),
        editAmount: false,
        payAmount: undefined,
        paymentDate: undefined,
        paymentSituation: '',
        paymentApprovalState: '',
        paymentComment: ''
      })
    },
    deletePayments(row, index) {
      this.removeObjWithArr(this.payments, row)
    },
    show(id) {
      this.dialogFormVisible = true
      this.contractId = id
      this.getContractDetail()
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = Object.assign({}, this.temp)
          // 更新payments
          if (this.payments !== undefined && this.payments.length > 0) {
            for (let i = 0; i < this.payments.length; i++) {
              if (this.payments[i].editAmount) {
                this.payments[i].proportion = (this.payments[i].payAmount * 100.00 / this.temp.contractAmount).toFixed(2)
              } else {
                this.payments[i].payAmount = (this.payments[i].proportion * 0.01 * this.temp.contractAmount).toFixed(2)
              }
            }
          }
          param.payments = this.payments
          putAction('/purchase/contract/update', param).then(({ msg }) => {
            this.dialogFormVisible = false
            Message.success(msg)
            this.$emit('handleChild', { type: 'contractUpdated' })
          })
        }
      })
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1) {
        const row1 = this.orderCodeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
      if (columnIndex === 9) {
        const row1 = this.projectNameArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
      if (columnIndex === 10) {
        const row1 = this.indentCodeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
      if (columnIndex === 11) {
        const row1 = this.supplierNameArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    },
    merage() {
      this.orderCodeArr = []
      this.projectNameArr = []
      this.indentCodeArr = []
      this.supplierNameArr = []

      let orderPos = 0
      let indentPos = 0
      let supplierPos = 0
      let projectPos = 0
      for (let i = 0; i < this.orderDetail.length; i++) {
        if (i === 0) {
          this.orderCodeArr.push(1)
          this.projectNameArr.push(1)
          this.indentCodeArr.push(1)
          this.supplierNameArr.push(1)
        } else {
          if (this.orderDetail[i].orderCode === this.orderDetail[i - 1].orderCode) {
            this.orderCodeArr[orderPos] += 1
            this.orderCodeArr.push(0)
          } else {
            this.orderCodeArr.push(1)
            orderPos = i
          }
          if (this.orderDetail[i].supplierName === this.orderDetail[i - 1].supplierName) {
            this.supplierNameArr[supplierPos] += 1
            this.supplierNameArr.push(0)
          } else {
            this.supplierNameArr.push(1)
            supplierPos = i
          }

          if (this.orderDetail[i].indentCode === this.orderDetail[i - 1].indentCode) {
            this.indentCodeArr[indentPos] += 1
            this.indentCodeArr.push(0)
          } else {
            this.indentCodeArr.push(1)
            indentPos = i
          }
          if (this.orderDetail[i].projectName === this.orderDetail[i - 1].projectName) {
            this.projectNameArr[projectPos] += 1
            this.projectNameArr.push(0)
          } else {
            this.projectNameArr.push(1)
            projectPos = i
          }
        }
      }
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.property !== 'materialTotalPrice') {
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          if (sums[index].toString().indexOf('.') > 1) {
            sums[index] = sums[index].toFixed(2)
          }
          // sums[index] += ' 元'
        }
      })

      return sums
    },
    btnPaymentOrder(row) {
      this.$refs.conPaymentOrderRef.btnPaymentOrder(row)
    },
    btnIndent(row) {
      this.$refs.conIndentOrderRef.btnIndent(row)
    },
    editAmountBtn(row) {
      row.editAmount = true
      row.payAmount = (row.proportion * 0.01 * this.temp.contractAmount).toFixed(2)
    },
    editPropBtn(row) {
      row.editAmount = false
      row.proportion = (row.payAmount * 100.00 / this.temp.contractAmount).toFixed(2)
    }

  }
}
</script>
